package cn.onein.edu.backend.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

import cn.onein.edu.common.MailType;
import cn.onein.edu.util.ResourceUtil;

/**
 * 邮件发送工具类 更多关于邮件发送的信息请参考用户指南：http://commons.apache.org/email/userguide.html
 * 
 * @author Upton
 * 
 */
public class EmailUtil {
	
	public final static String SERVICE_EMAIL;
	
	private static Logger logger = Logger.getLogger(EmailUtil.class);
	
	private static final String SMTP_HOST;
	private static final int SMTP_HOST_PORT;
	private static final String SMTP_AUTH_NAME;
	private static final String SMTP_AUTH_PASS;
	private static final String MAIL_FROM;
	private static final String MAIL_FROM_NAME;
	
	private static final Map<MailType,String> MailTemplatMaps = new HashMap<MailType,String>(); 

	static {
		ResourceBundle MailServerProperties = ResourceUtil.getMailServerProperties();
		SERVICE_EMAIL = MailServerProperties.getString("SERVICE_EMAIL");
		
		SMTP_HOST = MailServerProperties.getString("SMTP_HOST");
		SMTP_HOST_PORT = Integer.parseInt(MailServerProperties.getString("SMTP_HOST_PORT"));
		
		SMTP_AUTH_NAME = MailServerProperties.getString("SMTP_AUTH_NAME");
		SMTP_AUTH_PASS = MailServerProperties.getString("SMTP_AUTH_PASS");
		
		MAIL_FROM = MailServerProperties.getString("MAIL_FROM");
		MAIL_FROM_NAME = MailServerProperties.getString("MAIL_FROM_NAME");
		
		MailType[] types = MailType.values();
		
		logger.info("开始加载邮件模板……");
		for(MailType type : types){			
			InputStream inputS = null;
			BufferedReader reader = null;
			try{
				String templateFile = "/emailtemplate/" + type.toString() + ".html";
				inputS =  EmailUtil.class.getResourceAsStream(templateFile);
				reader = new BufferedReader(new InputStreamReader(inputS,"UTF-8"));
				
				StringBuffer template = new StringBuffer();
				
				String line = null;
				
				while((line = reader.readLine()) != null){
					template.append(line).append("\r\n");
				}
				
				MailTemplatMaps.put(type, template.toString());		
			}
			catch(IOException ex){
				logger.error(type.toString() + "的邮件模板加载失败~" , ex);
				
				throw new RuntimeException(type.toString() + "的邮件模板加载失败~",ex);
			}
			finally{
				try{
					if(inputS != null) inputS.close();
					if(reader != null) reader.close();
				}
				catch(IOException ex){
					logger.error(type.toString() + "的邮件模板加载失败~" , ex);
				}
			}
		}
		
		logger.info("结束加载邮件模板!");
	}

	/**
	 * 取得HTML的邮件
	 * @return HTML的邮件
	 * @throws EmailException
	 */
	public static HtmlEmail getHtmlEmail() throws EmailException {
		HtmlEmail email = new HtmlEmail();

		setMailServerArgs(email);

		return email;
	}
	
	/**
	 * 取得HTML的邮件
	 * @param 指定From邮件地址
	 * @return HTML的邮件
	 * @throws EmailException
	 */
	public static HtmlEmail getHtmlEmail(String fromEmail) throws EmailException {
		HtmlEmail email = new HtmlEmail();

		setMailServerArgs(email,fromEmail,fromEmail);

		return email;
	}
	
	/**
	 * 取得邮件模板
	 * @param mailType 邮件类型
	 * @return 对应的邮件模板
	 */
	public static String getEmailTemplate(MailType mailType){
		return getEmailTemplate(mailType,null);
	}
	
	/**
	 * 取得邮件模板
	 * @param mailType 邮件类型
	 * @param args 模板中的参数
	 * @return 对应的邮件模板
	 */
	public static String getEmailTemplate(MailType mailType,Object[] args){
		if(args != null && args.length > 0){
			return MessageFormat.format(MailTemplatMaps.get(mailType),args);
		}
		else{
			return MailTemplatMaps.get(mailType);
		}
	}

	private static void setMailServerArgs(Email email) throws EmailException {
		setMailServerArgs(email,MAIL_FROM, MAIL_FROM_NAME);
	}
	
	private static void setMailServerArgs(Email email, String fromEmail, String fromName) throws EmailException {
		email.setHostName(SMTP_HOST);
		email.setSmtpPort(SMTP_HOST_PORT);
		
		email.setAuthenticator(new DefaultAuthenticator(SMTP_AUTH_NAME, SMTP_AUTH_PASS));
		
		email.setCharset("UTF-8");
		email.setFrom(fromEmail, fromName, "UTF-8");
		
	}
	
	public static void main(String[] args) throws Exception {
		
			System.out.println(MessageFormat.format("a{0},b{1},c{1}",new Object[]{"0","1"}));
	}
}
